package com.hoperun.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.hoperun.bean.AdminOrganizations;
import com.hoperun.bean.AdminOrganizationsManager;
import com.hoperun.dao.AdminOrganizationsDAO;
import com.hoperun.dao.AdminOrganizationsManagerDAO;
import com.hoperun.framework.ex.XHZException;
import com.hoperun.framework.ibatis.page.BootGrid;
import com.hoperun.framework.ibatis.page.BootGridPage;
import com.hoperun.framework.query.Criteria;
import com.hoperun.framework.util.Constant;
import com.hoperun.service.IAdminOrganizationsManagerSV;
import com.hoperun.utils.ErrorCode;

@Service("adminOrganizationsManagerSV")
@Transactional
public class AdminOrganizationsManagerSVImpl implements
		IAdminOrganizationsManagerSV {
	@Resource
	private AdminOrganizationsManagerDAO adminOrganizationsManagerDAO;

	@Resource
	private AdminOrganizationsDAO adminOrganizationsDAO;

	@Override
	public void delete(Long id) throws Exception {
		// adminOrganizationsManagerDAO.delete(id);
	}

	@Override
	@Transactional(readOnly=true)
	public AdminOrganizationsManager queryById(Long id) throws Exception {
		return adminOrganizationsManagerDAO.queryById(id);
	}

	@Override
	public AdminOrganizationsManager save(
			AdminOrganizationsManager adminOrganizationsManager)
			throws Exception {
		adminOrganizationsManagerDAO.insert(adminOrganizationsManager);
		return adminOrganizationsManager;
	}

	@Override
	public void update(AdminOrganizationsManager adminOrganizationsManager)
			throws Exception {
		adminOrganizationsManagerDAO.update(adminOrganizationsManager);
	}

	@Override
	public void saveOrUpdate(AdminOrganizationsManager adminOrganizationsManager)
			throws Exception {
		if (adminOrganizationsManager == null)
			return;
		if (StringUtils.isNotBlank("" + adminOrganizationsManager.getOrgId())) {
			update(adminOrganizationsManager);
		} else {
			save(adminOrganizationsManager);
		}
	}

	@Override
	public void saveOrUpdate(List<AdminOrganizationsManager> list)
			throws Exception {
		if (CollectionUtils.isNotEmpty(list)) {
			for (AdminOrganizationsManager adminOrganizationsManager : list) {
				saveOrUpdate(adminOrganizationsManager);
			}
		}
	}

	@Override
	@Transactional(readOnly=true)
	public List<AdminOrganizationsManager> queryByCondition(Criteria criteria)
			throws Exception {
		return adminOrganizationsManagerDAO.queryByCondition(criteria);
	}

	@Override
	@Transactional(readOnly=true)
	public int queryCountByCondition(Criteria criteria) throws Exception {
		return adminOrganizationsManagerDAO.queryCountByCondition(criteria);
	}

	@Override
	@Transactional(readOnly=true)
	public BootGridPage<AdminOrganizationsManager> queryPage(Criteria criteria,
			BootGrid<AdminOrganizationsManager> grid) throws Exception {

		// AdminOrganizationsManager model = grid.getEntity();

		int totalCount = adminOrganizationsManagerDAO
				.queryCountByCondition(criteria);

		if (Constant.ZERO < totalCount) {

			Map<String, String> sorts = grid.getSort();

			/** 设置排序规则 **/
			if (MapUtils.isNotEmpty(sorts)) {
				Set<String> keySets = sorts.keySet();
				String sort = "";
				for (String key : keySets) {
					sort += " , " + key + " " + sorts.get(key);
				}
				criteria.orderBy(sort.replaceFirst(",", ""));
			}
			if (grid.getCurrent() >= Constant.ZERO) {
				int start = (grid.getCurrent() - Constant.ONE)
						* grid.getRowCount();
				int size = grid.getRowCount();

				criteria.limit(start, size);
			}
			List<AdminOrganizationsManager> list = adminOrganizationsManagerDAO
					.queryByCondition(criteria);
			BootGridPage<AdminOrganizationsManager> page = new BootGridPage<AdminOrganizationsManager>(
					grid.getCurrent(), grid.getRowCount(), totalCount, list);

			return page;
		}
		return new BootGridPage<AdminOrganizationsManager>(grid.getCurrent(),
				grid.getRowCount(), totalCount,
				new ArrayList<AdminOrganizationsManager>());

	}

	/**
	 * 按条件查询记录记录
	 * 
	 * @param criteria
	 * @throws Exception
	 */
	@Override
	@Transactional(readOnly=true)
	public List<AdminOrganizationsManager> queryBySpecificCondition(
			Criteria criteria) throws Exception {
		return adminOrganizationsManagerDAO.queryBySpecificCondition(criteria);
	}

	/**
	 * 按条件查询记录条数
	 * 
	 * @param criteria
	 * @throws Exception
	 */
	@Override
	@Transactional(readOnly=true)
	public int queryCountBySpecificCondition(Criteria criteria)
			throws Exception {
		return adminOrganizationsManagerDAO
				.queryCountBySpecificCondition(criteria);
	}

	/**
	 * 分页查询
	 * 
	 * @param criteria
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(readOnly=true)
	public BootGridPage<AdminOrganizationsManager> querySpecificPage(
			Criteria criteria, BootGrid<AdminOrganizationsManager> grid)
			throws Exception {

		// AdminOrganizationsManager model = grid.getEntity();

		int totalCount = adminOrganizationsManagerDAO
				.queryCountBySpecificCondition(criteria);

		if (Constant.ZERO < totalCount) {

			Map<String, String> sorts = grid.getSort();

			/** 设置排序规则 **/
			if (MapUtils.isNotEmpty(sorts)) {
				Set<String> keySets = sorts.keySet();
				String sort = "";
				for (String key : keySets) {
					sort += " , " + key + " " + sorts.get(key);
				}
				criteria.orderBy(sort.replaceFirst(",", ""));
			}
			if (grid.getCurrent() >= Constant.ZERO) {
				int start = (grid.getCurrent() - Constant.ONE)
						* grid.getRowCount();
				int size = grid.getRowCount();

				criteria.limit(start, size);
			}
			List<AdminOrganizationsManager> list = adminOrganizationsManagerDAO
					.queryBySpecificCondition(criteria);
			BootGridPage<AdminOrganizationsManager> page = new BootGridPage<AdminOrganizationsManager>(
					grid.getCurrent(), grid.getRowCount(), totalCount, list);

			return page;
		}
		return new BootGridPage<AdminOrganizationsManager>(grid.getCurrent(),
				grid.getRowCount(), totalCount,
				new ArrayList<AdminOrganizationsManager>());

	}

	@Override
	@Transactional(readOnly=true)
	public List<AdminOrganizations> queryManagerMaxOrganization(Long managerId,
			Long orgId) throws Exception {

		if (null == orgId || orgId < Constant.ONE) {
			return organizations(managerId);
		} else {
			Criteria criteria = new Criteria();
			criteria.addEqual(AdminOrganizations.COL_PARENT_ID, orgId,
					Criteria.AND);
			criteria.orderBy(AdminOrganizations.COL_SORT + " DESC ");

			return adminOrganizationsDAO.queryByCondition(criteria);
		}

	}

	private List<AdminOrganizations> organizations(Long managerId)
			throws Exception {
		Criteria criteria = new Criteria(AdminOrganizationsManager.TABLE_PREFIX);
		criteria.addEqual(AdminOrganizationsManager.COL_MANAGER_ID, managerId,
				Criteria.AND);
		List<AdminOrganizationsManager> organizationsManagers = adminOrganizationsManagerDAO
				.queryBySpecificCondition(criteria);
		List<AdminOrganizations> organizations = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(organizationsManagers)) {
			/** 根据组织机构编码降序排越小越排在顶端 */
			for (AdminOrganizationsManager organizationsManager : organizationsManagers) {

				if (null != organizationsManager.getAdminOrganizations()
						&& StringUtils.isNotBlank(organizationsManager
								.getAdminOrganizations().getOrgCode())) {
					organizations.add(organizationsManager
							.getAdminOrganizations());
				}
			}

			Collections.sort(organizations,
					new Comparator<AdminOrganizations>() {
						public int compare(AdminOrganizations arg0,
								AdminOrganizations arg1) {
							return arg0.getOrgCode().compareTo(
									arg1.getOrgCode());
						}
					});
		}
		return organizations;
	}

	@Override
	public List<AdminOrganizationsManager> createBind(String oids, String mids)
			throws Exception {
		if (StringUtils.isBlank(oids) || StringUtils.isBlank(mids)) {
			throw new XHZException(ErrorCode.ILLEGAL_REQUEST.ERROR_REQUEST);
		}

		String[] oidsArray = oids.split(",");
		String[] midsArray = mids.split(",");
		List<AdminOrganizationsManager> result = Lists.newArrayList();

		if (ArrayUtils.isEmpty(oidsArray) || ArrayUtils.isEmpty(midsArray)) {
			throw new XHZException(ErrorCode.ILLEGAL_REQUEST.ERROR_REQUEST);
		}

		for (String mid : Arrays.asList(midsArray)) {
			AdminOrganizationsManager delete = new AdminOrganizationsManager();
			delete.setManagerId(Long.valueOf(mid));
			/** 删除之前的关联 */
			adminOrganizationsManagerDAO.delete(delete);

			/** 添加新的关联 */
			for (String oid : Arrays.asList(oidsArray)) {
				AdminOrganizationsManager organizationsManager = new AdminOrganizationsManager();
				organizationsManager.setOrgId(Long.valueOf(oid));
				organizationsManager.setManagerId(Long.valueOf(mid));

				adminOrganizationsManagerDAO.insert(organizationsManager);

				result.add(organizationsManager);
			}
		}

		return result;
	}

	@Override
	public void deleteBindManager(String mids) throws Exception {
		if (StringUtils.isBlank(mids)) {
			throw new XHZException(ErrorCode.ILLEGAL_REQUEST.ERROR_REQUEST);
		}

		String[] midsArray = mids.split(",");

		if (ArrayUtils.isEmpty(midsArray)) {
			throw new XHZException(ErrorCode.ILLEGAL_REQUEST.ERROR_REQUEST);
		}

		for (String mid : Arrays.asList(midsArray)) {
			AdminOrganizationsManager delete = new AdminOrganizationsManager();
			delete.setManagerId(Long.valueOf(mid));
			/** 删除之前的关联 */
			adminOrganizationsManagerDAO.delete(delete);

		}

	}

}
